package com.njtoyo.taxi.admin.service.business.operation_rule.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njtoyo.taxi.admin.cache.PrimaryCachePutter;
import com.njtoyo.taxi.admin.mapper.master.entity.CallDispatchRule;
import com.njtoyo.taxi.admin.mapper.master.mapper.CallDispatchRuleMapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.dispatch_rule.DispatchFormDataWrapper;
import com.njtoyo.taxi.admin.service.business.operation_rule.CallDispatchRuleService;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CallDispatchRuleServiceImpl extends ServiceImpl<CallDispatchRuleMapper, CallDispatchRule> implements CallDispatchRuleService {
    @Autowired
    private PrimaryCachePutter primaryCachePutter;

    @Override
    public RestResult set(DispatchFormDataWrapper formData) {
        CallDispatchRule callDispatchRule = baseMapper.selectOne(Wrappers.<CallDispatchRule>lambdaQuery().eq(CallDispatchRule::getDriverRegionId, formData.getDriverRegionId()));
        CallDispatchRule stt = new CallDispatchRule();
        stt.setIsActive(true);
        stt.setDriverRegionId(formData.getDriverRegionId());
        stt.setTriggerDistance(formData.getTriggerDistance());
        stt.setDispatchDistanceMax(formData.getDispatchDistanceMax());
        stt.setWeightSpec(JSON.toJSONString(Dict.create()
                .set("score", formData.getScore())
                .set("distance", formData.getDistance())));
        if (ObjectUtil.isNull(callDispatchRule)) {
            baseMapper.insert(stt);
        } else {
            stt.setId(callDispatchRule.getId());
            baseMapper.updateById(stt);
        }
        primaryCachePutter.getRedisTemplate().delete("dispatch:call:rule:" + formData.getDriverRegionId());
        return RestResult.success();
    }

    @Override
    public RestResult getDetailByRegionId(Long id) {
        CallDispatchRule callDispatchRule = baseMapper.selectOne(Wrappers.<CallDispatchRule>lambdaQuery().eq(CallDispatchRule::getDriverRegionId, id));
        return RestResult.success(callDispatchRule);
    }
}
